# coding=utf-8
#

import json

from datetime import datetime
from django.conf import settings

from iminer.agent.models import Agent
from iminer.agent.models import AgentHeartbeat

from iminer.utils.redis import redis_proxy

from iminer.utils.http import make_api_response

from iminer.utils.decorator import check_user
from iminer.utils.decorator import check_user_with_cache

from iminer.sm_log import getLogger

logger = getLogger("iminer.agent.views")


def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('HTTP_X_REAL_IP') or request.META.get('REMOTE_ADDR')
    return ip


@check_user
def report_agent_status(request, *args, **kwargs):
    """
    上报agent的状态

    Args:
        :params: body

    Returns:
        {}
    """

    data = json.loads(request.body)

    alias = data.get("alias", "")
    idc = data.get("idc", "")
    cpu = data.get("cpu", 0)
    local_its = data.get("local_its", 0)
    local_avg_its = data.get("local_avg_its", 0)
    source = data.get("source", "") or "qm"

    if source:
        agent, _ = Agent.objects.get_or_create(alias=alias, status=1)

        agent.idc = idc
        agent.cpu = cpu
        agent.local_its = local_its
        agent.local_avg_its = local_avg_its
        agent.status = 1

        if local_its and local_avg_its:
            agent.last_active = datetime.now()
            AgentHeartbeat(alias=alias,
                           local_its=local_its,
                           cpu=cpu,
                           local_avg_its=local_avg_its,
                           cur_time=datetime.now()).save()

        agent.save()

    return make_api_response({})


@check_user_with_cache
def async_report_agent_status(request, *args, **kwargs):

    data = json.loads(request.body)
    source = data.get("source", "")

    if source == "tencent":
        return make_api_response({})

    ip = get_client_ip(request)

    data["ip"] = ip

    redis_proxy.r.lpush(settings.DATA_QUEUE, json.dumps(data))
    return make_api_response({})


@check_user_with_cache
def report_hw_agent(request, *args, **kwargs):
    """ """
    data = json.loads(request.body)

    idc = "hw"
    az = data.get("az", "")
    project_id = data.get("project_id", "")
    server_ids = data.get("server_ids", "")

    logger.info("Got: %s" % json.dumps(data))

    return make_api_response({})

    for alias, server_id in server_ids:
        agent, _ = Agent.objects.filter(alias=alias, idc=idc)
        agent.server_id = server_id
        agent.az = az
        agent.project_id = project_id
        agent.status = 1
        agent.save()

    return make_api_response({})

